﻿using UnityEngine;
using System.Collections;

public class Magnet : MonoBehaviour//磁体
{
    [Range(0f, 10f)]
    public float AttractionRange = 5f;
    [Range(0f, 30f)]
    public float AttractionFactor = 4f;
    [Range(0.5f, 50f)]
    public float Mass = 0.5f;
    public Transform RangeSprite;
    new Rigidbody2D rigidbody2D;

    Transform range;
    private void Awake()
    {
        rigidbody2D = GetComponent<Rigidbody2D>();
        if (rigidbody2D != null) rigidbody2D.mass = Mass;
        range = Instantiate(RangeSprite);
        range.localScale = new Vector3(AttractionRange * 2f, AttractionRange * 2f, 1);
    }
    private void FixedUpdate()
    {
        Collider2D[] cols = Physics2D.OverlapCircleAll(transform.position, AttractionRange, Constants.LayerMask_Ferromagnetism | Constants.LayerMask_Magnet);
        Vector2 totalForce = Vector2.zero;
        foreach (Collider2D item in cols)
        {
            if (item.transform != transform)
            {
                Rigidbody2D rgd = item.GetComponent<Rigidbody2D>();
                Vector2 force = rgd.transform.position - transform.position;
                force = force / force.sqrMagnitude * Mass * AttractionFactor;
                if (rgd != null) 
                    rgd.AddForce(-force);
                totalForce += force;
            }
        }
        if (rigidbody2D != null)
            rigidbody2D.AddForce(totalForce);
        range.position = transform.position;
    }
}
